#!/usr/bin/python
# 
# label: [ url,
#     {
#        item : [ pattern, lambda, p1, p2 ],
#        ...
#     }
# ],
#
# ** Warehouse  
#       {   number,
#           label:box, "...", "..." }
#    Just like its name. It is a place where store and manager the user boxes. 
#    for now we just locked the boxes into the macache, maybe to database in furture.
#
# ** box   
#       { url,
#         item:stuff, "...", "..." }
#    Users would put everything they needed into a box, deposited the box in Warehouse.
#
# ** sutff
#       { pattern, value }
#    There are many stuff in a box, a stuff is combined with a pattern(regular express) and a value(matched)
#
from google.appengine.api import memcache
import logging

class stuff:
    def __init__(self, param):
        self.param = param
        self.val=""
        self.ref=""

    def update(self, param):
        if (self.param == param):
            return None
        else:
            self.param = param
            return "OK"

    def set(self,value):
        if self.val == value:
            return None
        else:
            self.val=value
            if self.ref == "":
                self.ref = value
            return "OK"

    def getpattern(self):
        return self.param[0]

    def getlambda(self):
        return self.param[1], self.param[2], self.param[3]

    def getvalue(self):
        return self.val, self.ref

    def keepref(self):
        self.ref=self.val

class box:
    def __init__(self, pack):
        self.status = "OPENED"
        self.url = pack[0]
        self.stuffs=dict()
        for k,v in pack[1].items():
            self.stuffs[k] = stuff(v)

    def update(self, pack):
        self.status = "SEALED"
        if self.url != pack[0]:
            self.url = pack[0]
            self.status = "OPENED"
        for k,v in pack[1].items():
            if self.stuffs[k].update(v) is not None:
                self.status = "OPENED"

    def seal(self):
        self.status = "SEALED"

    def setitem(self, item, value):
        if item in self.stuffs:
            if self.stuffs[item].set(value) is not None:
                self.status = "OPENED"
                #logging.info("<%s> was changed", item)
        else:
            logging.error("Can't edit a unexisted item <%s> ", item)
            raise NameError, item

    def keepref(self):
        for stuff in self.stuffs.values():
            stuff.keepref()

class Warehouse:
    def __init__(self, doorplate):
        self.doorplate = doorplate

    def CHECKIN(self, label, box):
        memcache.set(label,box,
                namespace=self.doorplate)

    def CHECKOUT(self, label):
        box = memcache.get(label,
                namespace=self.doorplate)
        if box is not None:
            box.seal()
        return box

